// 拉流
import axios from "axios";

export function doOfferPull(userId: string, roomId: string) {
  var remoteVideo = document.getElementById("remoteVideo") as HTMLVideoElement;

  // 创建RTCPeerConnection
  var pc = new RTCPeerConnection(null); // 音视频通话的核心类
  pc.ontrack = function (event) {
    remoteVideo.srcObject = event.streams[0];
  };

  // 创建并发送 offer message
  pc.createOffer({
    offerToReceiveAudio: true,
    offerToReceiveVideo: true,
  })
    .then(function (offer) {
      pc.setLocalDescription(offer)
        .then(function () {
          var uri = "/rtc/v1/play/";
          var data = {
            api: uri,
            sdp: offer.sdp,
            streamurl: `webrtc://live/livestream/${roomId}`,
            tid: userId,
          };
          console.log("offer data: ", data);
          axios.post(uri, data).then((response) => {
            console.log("answer data: ", response.data);
            pc.setRemoteDescription({
              type: "answer",
              sdp: response.data.sdp,
            }).then(() => {});
          });
        })
        .catch(function (error) {
          console.error("offer setLocalDescription failed: " + error);
        });
    })
    .catch(function (error) {
      console.error("doOffer failed: " + error);
    });
}
